package cn.bluech.lib.utils;

/**
 * Description: 按bit流读取，从高位开启取，放在高位，低位补0
 *              如：{0x5A}取4个bit就是{0x50}
 * Created by Codeant on 2019/5/14.
 */
public class BitInputStream {
    private byte[] data;
    private int pos;
    private int len;

    public BitInputStream(byte[] data){
        this.data = data;
        pos = 0;
        len = null!=data?data.length*8:0;
    }

    public final int remaining() {
        //throw new RuntimeException("Stub!");
        return len-pos;
    }

    public final boolean hasRemaining() {
        return len>pos;
    }

    public boolean getBit(){
        if(!hasRemaining())
            return false; // 这里可能要抛出异常

        byte value = data[pos/8];

        return ((value<<(pos++%8))&0x80)==0x80;
    }

    public byte[] getBits(int len){
        byte[] buf;
        int remaining = remaining();

        if(len>remaining){
            len = remaining;
            // 这里可能要抛出异常
        }
        if(len==0)
            return null;

        if(len%8==0)
            buf = new byte[len/8];
        else
            buf = new byte[len/8+1];

        // 简单方式
        for(int i=0;i<len;){
            for(int j=0;(j<8)&&(i<len);j++,i++){
                if(getBit())
                    buf[i/8] |= 0x80>>>j;
            }
        }

        return buf;
    }
}
